<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="食材名称" prop="foodName">
        <el-input
          v-model="queryParams.foodName"
          placeholder="请输入食材名称"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="食材进度" prop="status">
        <el-select
          v-model="queryParams.status"
          placeholder="请选择进度"
          clearable
        >
          <el-option
            label="有剩余"
            value="0"
          ></el-option>
          <el-option
            label="已用完"
            value="1"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
          v-hasPermi="['manage:food:add']"
        >新增</el-button>
      </el-col>
      <!-- <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="Edit"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['manage:food:edit']"
        >修改</el-button>
      </el-col> -->
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="Delete"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['manage:food:remove']"
        >删除</el-button>
      </el-col>
      <!-- <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="Download"
          @click="handleExport"
          v-hasPermi="['manage:food:export']"
        >导出</el-button>
      </el-col> -->
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="foodList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="序号" type="index" width="50" align="center" />
      <el-table-column label="食材名称" align="center" prop="foodName" width="180" />
      <el-table-column label="食材图片" align="center" prop="imageUrl" width="100">
        <template #default="scope">
          <image-preview :src="scope.row.imageUrl" :width="50" :height="50"/>
        </template>
      </el-table-column>
      <!-- <el-table-column label="生产日期" align="center" prop="produceDate" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.produceDate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column> -->
      <!-- <el-table-column label="保质期" align="center" prop="shelfLife" /> -->
      <el-table-column label="录入时间" align="center" prop="createTime" width="160" sortable>
        <template #default="scope">
          <span>{{ parseTime(scope.row.createTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="期望食用时间" align="center" prop="useTime" width="160" sortable>
        <template #default="scope">
          <span>{{ parseTime(scope.row.useTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="食用进度" align="center" prop="status">
        <template #default="scope">
          <el-tag v-if="scope.row.status === 0">有剩余</el-tag>
          <el-tag v-else type="success">已用完</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="食材类型" align="center" prop="foodTypeName" />
      <el-table-column label="食材总量" align="center" prop="foodTotal">
        <template #default="scope">
          <span>{{ scope.row.foodTotal }} {{ getUnitName(scope.row.unitId) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="已食用的量" align="center" prop="consumption" width="100">
        <template #default="scope">
          <span v-if="scope.row.consumption != 0">{{ scope.row.consumption }} {{ getUnitName(scope.row.unitId) }}</span>
          <span v-else>暂未食用</span>
        </template>
      </el-table-column>
      <!-- <el-table-column label="单位" align="center" prop="unitId">
        <template #default="scope">
          <dict-tag :options="product_unit" :value="scope.row.unitId"/>
        </template>
      </el-table-column> -->
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="200">
        <template #default="scope">
          <el-button link type="primary" icon="Notification" @click="handleDetail(scope.row)" v-hasPermi="['manage:food:list']">详情</el-button>
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['manage:food:edit']">修改</el-button>
          <el-button link type="danger" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['manage:food:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改食材对话框 -->
    <el-dialog :title="title" v-model="open" width="550px" append-to-body>
      <el-form ref="foodRef" :model="form" :rules="rules" label-width="auto" class="form-container">
        <el-row>
          <el-form-item label="食材名称" prop="foodName">
            <el-input v-model="form.foodName" placeholder="请输入食材名称" />
          </el-form-item>
          <el-form-item label="食材图片" prop="imageUrl">
            <image-upload v-model="form.imageUrl" :limit="1" />
          </el-form-item>
          <el-form-item label="食材类型" prop="foodType">
              <el-cascader 
              v-model="form.foodType" 
              placeholder="请选择"
              :options="foodTypeList"
              :props="{ value: 'foodTypeId', label: 'foodTypeName', children: 'children', emitPath: false }"
              :show-all-levels="false"
              clearable
              @change="handleChange"
              />
          </el-form-item>
          <el-divider>食材期限</el-divider>
          <el-form-item label="生产日期" prop="produceDate">
            <el-date-picker clearable
              v-model="form.produceDate"
              type="datetime"
              value-format="YYYY-MM-DD HH:mm:ss"
              placeholder="请选择生产日期">
            </el-date-picker>
          </el-form-item>
          <el-form-item label="保质期" prop="shelfLife">
            <el-input-number v-model="form.shelfLife" 
              placeholder="请输入保质期"
              :min="0" 
              :step="0.1" 
              :precision="1" 
              style="width: 185px;"
            />
            <span style="margin-left: 20px">天</span>
          </el-form-item>
          <el-form-item label="期望食用时间" prop="useTime">
            <el-date-picker clearable
              v-model="form.useTime"
              type="datetime"
              value-format="YYYY-MM-DD HH:mm:ss"
              placeholder="请选择期望食用时间">
            </el-date-picker>
          </el-form-item>
          <el-divider>食材量</el-divider>
          <div class="form-row">
            <el-form-item label="食材总量" prop="foodTotal">
              <el-input-number 
                v-model="form.foodTotal" 
                placeholder="食材总量" 
                :min="0" 
                :step="0.1" 
                :precision="1"
                style="width: 175px;"
              />
            </el-form-item>
            <el-form-item label="单位" prop="unitId">
              <el-select v-model="form.unitId" placeholder="请选择" clearable style="width: 140px;">
                <el-option
                  v-for="dict in product_unit"
                  :key="dict.value"
                  :label="dict.label"
                  :value="parseInt(dict.value)"
                ></el-option>
              </el-select>
            </el-form-item>
          </div>
          <el-form-item prop="consumption">
            <template v-slot:label>
              <div style="display: flex; align-items: center;">
                <span>已食用的量</span>
                <el-tooltip class="item" effect="dark" placement="bottom">
                  <el-icon style="margin-left: 5px;"><QuestionFilled /></el-icon>
                  <template #content>本项选填：若食材未食用，可不填</template>
                </el-tooltip>
              </div>
            </template>
            <el-input-number v-model="form.consumption" placeholder="已食用的量" style="width: 160px;" :min="0" :step="0.1" :precision="1" />
          </el-form-item>
        </el-row>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 食材详情对话框 -->
    <el-drawer
      v-model="drawer"
      :title="title"
      direction="rtl"
      size="40%"
      class="custom-drawer"
    >
      <el-descriptions title="食材信息" border>
        <el-descriptions-item
          :span="3"
          :width="110"
          label="食材图片"
          align="center"
        >
        <image-preview :src="form.imageUrl" :width="100" :height="100" />
        </el-descriptions-item>
        <el-descriptions-item label="食材名称" :span="2" align="center">{{ form.foodName }}</el-descriptions-item>
        <el-descriptions-item label="食材类型" align="center">{{ form.foodTypeName }}</el-descriptions-item>
      </el-descriptions>
      <el-descriptions title="食材有关日期" border style="margin-top: 50px;" :column="2">
        <el-descriptions-item label="生产日期" align="center">{{ parseTime(form.produceDate, '{y}-{m}-{d} {h}:{i}:{s}') }}</el-descriptions-item>
        <el-descriptions-item label="保质期" align="center">{{ form.shelfLife }} 天</el-descriptions-item>
        <el-descriptions-item label="期望食用时间" align="center">{{ parseTime(form.useTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</el-descriptions-item>
        <el-descriptions-item label="距离过期时间剩" align="center">
          <span v-if="calculateRemainingDays(form.produceDate, form.shelfLife) != 0">
            {{ calculateRemainingDays(form.produceDate, form.shelfLife) }} 天
          </span>
          <span v-else>已过期</span>
        </el-descriptions-item>
      </el-descriptions>
      <el-descriptions title="食材进度" border style="margin-top: 50px;" :column="2">
        <el-descriptions-item label="食材总量" align="center">{{ form.foodTotal }} {{ getUnitName(form.unitId) }}</el-descriptions-item>
        <el-descriptions-item label="已食用量" align="center">
          <span v-if="form.consumption != 0">{{ form.consumption }} {{ getUnitName(form.unitId) }}</span>
          <span v-else>暂未食用</span>
        </el-descriptions-item>
        <el-descriptions-item label="进度" align="center">
          <el-progress 
          type="dashboard" 
          :percentage="calculateProgress(form.consumption, form.foodTotal)" 
          :status="calculateProgress(form.consumption, form.foodTotal) < 50 ? 'exception' : calculateProgress(form.consumption, form.foodTotal) < 80 ? 'warning' : ''">
            <template #default="{ percentage }">
              <span class="percentage-value">{{ percentage }}%</span>
              <span class="percentage-label">目前进度</span>
            </template>
          </el-progress>
        </el-descriptions-item>
      </el-descriptions>
    </el-drawer>
  </div>
</template>

<script setup name="Food">
import { listFood, getFood, delFood, addFood, updateFood } from "@/api/manage/food";
import { listFoodType } from "@/api/manage/foodType"
import dayjs from 'dayjs';
import utc from 'dayjs/plugin/utc'; // 引入 UTC 插件
import timezone from 'dayjs/plugin/timezone'; // 引入时区插件
import { ref, onMounted, watch } from "vue"
import { useRoute } from "vue-router"

// 监听 URL 参数变化
const route = useRoute();

const { proxy } = getCurrentInstance();
const { product_unit } = proxy.useDict('product_unit');

const foodList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");
const drawer = ref(false);

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    foodName: null,
    useTime: null,
    status: null,
    foodType: null,
  },
  rules: {
    foodName: [
      { required: true, message: "食材名称不能为空", trigger: "blur" }
    ],
    foodType: [
      { required: true, message: "请选择食材类型", trigger: "change" }
    ],
    produceDate: [
      { type: 'date', required: true, message: "请选择生产日期", trigger: "change" }
    ],
    shelfLife: [
      { required: true, message: "保质期不能为空", trigger: "blur" }
    ],
    useTime: [
      { type: 'date', required: true, message: "请选择期望食用时间", trigger: "change" }
    ],
    foodTotal: [
      { required: true, message: "食材总量不能为空", trigger: "blur" }
    ],
    unitId: [
      { required: true, message: "请选择单位", trigger: "change" }
    ],
  }
});

const { queryParams, form, rules } = toRefs(data);

/** 查询食材列表 */
function getList() {
  loading.value = true;
  listFood(queryParams.value).then(response => {
    foodList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    foodId: null,
    foodName: null,
    produceDate: null,
    shelfLife: null,
    createTime: null,
    useTime: null,
    imageUrl: null,
    status: null,
    foodType: null,
    foodTotal: null,
    unitId: null,
    consumption: null
  };
  proxy.resetForm("foodRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.foodId);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  getFoodTypeList()
  open.value = true;
  title.value = "添加食材";
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  const _foodId = row.foodId || ids.value
  getFood(_foodId).then(response => {
    form.value = response.data;
    open.value = true;
    title.value = "修改食材";
  });
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["foodRef"].validate(valid => {
    if (valid) {
      if (form.value.foodId != null) {
        updateFood(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        console.log("addform", form.value);
        addFood(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _foodIds = row.foodId || ids.value;
  const delName = _foodIds.length >= 1 ? '选中的食材' : row.foodName
  proxy.$modal.confirm('确定要删除' + delName + '吗？').then(function() {
    return delFood(_foodIds);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => {});
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('manage/food/export', {
    ...queryParams.value
  }, `food_${new Date().getTime()}.xlsx`)
}

const foodTypeList = ref([]);

// 辅助函数来检查项目及其所有祖先是否都已启用
const isFullyEnabled = (item, allItems) => {
  if (item.isEnabled !== 1) return false;
  if (item.parentId === 0) return true; // 如果没有父级，直接返回true
  const parent = allItems.find(parentItem => parentItem.foodTypeId === item.parentId);
  return parent ? isFullyEnabled(parent, allItems) : false;
}

/** 查询食材类型下拉列表 */
function getFoodTypeList() {
  listFoodType().then(response => {
    const resData = response.data;
    // 过滤数据
    const dataList = resData.filter(item => isFullyEnabled(item, resData));
    // 赋值给foodTypeList
    foodTypeList.value = proxy.handleTree(dataList, "foodTypeId", "parentId");
  });
}

// 监测勾选
const handleChange = (value) => {
  console.log(value)
}

/** 详情按钮操作 **/
function handleDetail(row) {
  form.value = { ...row };
  console.log("form", form.value);
  drawer.value = true;
  title.value = "食材详情";
}

// 获取单位名称
const getUnitName = (unitId) => {
  console.log("unitId", unitId);
  console.log("product_unit", product_unit.value);
  const unitOption = product_unit.value.find(option => parseInt(option.value) === unitId);
  console.log("unitOption", unitOption);
  return unitOption ? unitOption.label : '';
};

// 计算食用进度
const calculateProgress = (consumption, total) => {
  // 验证输入是否为有效数字
  if (typeof consumption !== 'number' || typeof total !== 'number' || total <= 0) {
    return 0; // 或者根据业务逻辑选择其他合理的默认值
  }

  // 计算进度并四舍五入到整数
  const progress = Math.round((consumption / total) * 100);

  // 确保进度在 0 到 100 的范围内
  return Math.min(100, Math.max(0, progress));
};

// 使用 UTC 和时区插件
dayjs.extend(utc);
dayjs.extend(timezone);

// 计算距离过期时间
const calculateRemainingDays = (proDate, shelfDate) => {
  const now = dayjs().utc(); // 获取当前 UTC 时间
  const produceDate = dayjs(proDate).utc(); // 生产日期转为 UTC
  const shelfLifeDays = shelfDate; // 保质期天数
  // 计算过期日期（UTC）
  const expireDate = produceDate.add(shelfLifeDays, 'day');
  // 计算剩余时间（以天为单位）
  const remainingMilliseconds = expireDate.diff(now);
  const remainingDays = Math.ceil(remainingMilliseconds / (1000 * 60 * 60 * 24));
  // 如果已经过期，则返回0
  return remainingDays > 0 ? remainingDays : 0;
};

// 通过 URL 获取查询参数
onMounted(() => {
  const params = new URLSearchParams(window.location.search);
  if (params.has('foodName')) {
    queryParams.value.foodName = params.get('foodName');
  }
  if (params.has('status')) {
    queryParams.value.status = params.get('status');
  }
  handleQuery(); // 执行查询
});

// 监听 foodName 参数变化
watch(() => route.query.foodName, (newFoodName) => {
  if (newFoodName !== undefined) {
    queryParams.value.foodName = newFoodName;
    queryParams.value.pageNum = 1; // 重置页码
    handleQuery(); // 重新执行查询
  }
});

getFoodTypeList()
getList();
</script>

<style scope>
.percentage-value {
  display: block;
  margin-top: 10px;
  font-size: 28px;
}
.percentage-label {
  display: block;
  margin-top: 10px;
  font-size: 12px;
}

/* 调整抽屉标题与内容之间的间距 */
.custom-drawer .el-drawer__header {
  margin-bottom: 10px; /* 减小标题与内容之间的间距 */
}

.form-container span {
  font-size: 14px;
  font-weight: 700;
  margin-left: 10px;
}

.form-container .form-row {
  display: flex;
}
</style>
